<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="5" :xs="24">
        <div class="head-container">
          <el-tree
            :data="ouTree"
            :expand-on-click-node="false"
            ref="tree"
            node-key="id"
            lazy
            :props="treeProps"
            :load="getSubTree"
            :default-expanded-keys="expandKeys"
            highlight-current
            @current-change="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="19" :xs="24">
        <el-form
          size="mini"
          :model="queryParams"
          ref="queryForm"
          class="queryForm"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item prop="displayName">
            <el-input
              v-model="queryParams.displayName"
              placeholder="组名称"
              clearable
              @keyup.enter.native="handleQuery"
            >
              <el-select
                v-model="queryParams.searchScope"
                slot="prepend"
                placeholder="搜索范围"
              >
                <el-option label="全局搜索" value="global"></el-option>
                <el-option label="当前组织" value="current"></el-option>
              </el-select>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAddGroup"
              >新增</el-button
            >
            <el-button
              icon="el-icon-download"
              size="mini"
              @click="exportGroupExcel"
              >导出</el-button
            >
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="userList" class="dense-table">
          <el-table-column
            label="组账号"
            align="left"
            key="samAccountName"
            prop="samAccountName"
          >
            <template scope="scope">
              <el-link type="primary" @click="showInfo(scope.row)">{{
                scope.row.samAccountName
              }}</el-link>
            </template>
          </el-table-column>
          <el-table-column label="组名" align="left" key="name" prop="name" />
          <el-table-column
            label="组类型"
            align="left"
            key="groupType"
            prop="groupType"
          />
          <el-table-column
            label="创建时间"
            align="left"
            key="whenCreated"
            prop="whenCreated"
          />
          <el-table-column
            label="操作"
            align="left"
            width="100px"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                v-hasPermi="['system:menu:delete']"
                @click="handleDeleteGroup(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 用户详情抽屉 -->
    <el-drawer
      :withHeader="false"
      size="650px"
      v-if="currentGroup"
      :visible.sync="groupDetailDrawerVisible"
      direction="rtl"
      class="detail-drawer"
      :modal="false"
    >
      <div style="padding: 20px 15px" v-loading="infoLoading">
        <h3>
          <span> {{ currentGroup.name || currentGroup.samAccountName }}</span>
        </h3>
        <h4 class="info-group-header">基本信息</h4>
        <div class="info-item">
          <span class="info-label">组账号:</span>
          <span>{{ currentGroup.samAccountName }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">组类型:</span>
          <span>{{ currentGroup.groupType }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">组位置:</span>
          <span>{{ currentGroup.distinguishedName }}</span>
        </div>
        <!-- <div class="info-item">
          <span class="info-label">objectCategory:</span>
          <span>{{ currentGroup.objectCategory }}</span>
        </div> -->

        <el-divider></el-divider>
        <h4 class="info-group-header">
          成员信息
          <span
            style="line-height: 35px; font-weight: 500"
            v-if="members.total > 0"
            >（{{ members.total }}）</span
          >
          <el-link style="float: right" @click="showMembersManage()"
            >管理<i class="el-icon-arrow-right"></i
          ></el-link>
        </h4>
        <el-row>
          <el-col :span="9">
            <el-input
              size="mini"
              placeholder="输入显示名,回车检索"
              prefix-icon="el-icon-search"
              v-model="members.query.displayName"
              @keyup.enter.native="getMembers()"
            ></el-input>
          </el-col>
        </el-row>
        <div style="padding: 5px 0">
          <el-table
            class="dense-table"
            v-loading="members.loading"
            element-loading-text="正在加载"
            :data="members.list"
            height="calc(100vh - 395px)"
          >
            <el-table-column
              label="员工编号"
              align="left"
              key="description"
              prop="description"
            >
              <template scope="scope">
                <svg-icon
                  :icon-class="getIcon(scope.row)"
                  style="margin-right: 5px"
                />{{ scope.row.description }}
              </template>
            </el-table-column>
            <el-table-column label="姓名" align="left" key="cn" prop="cn">
            </el-table-column>
          </el-table>

          <pagination
            v-show="members.total > 0"
            :total="members.total"
            :page.sync="members.query.pageNum"
            :limit.sync="members.query.pageSize"
            @pagination="getMembers"
          />
        </div>
      </div>
      <el-form v-if="currentGroup" :model="currentGroup"></el-form>
    </el-drawer>
  </div>
</template>

<script>
import ouApi from "@/api/activeDirectory/ou";
import groupApi from "@/api/activeDirectory/group";
import { orgMixin } from "../mixin/org";
export default {
  name: "group",
  mixins: [orgMixin],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",

      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      currentGroup: undefined,
      groupDetailDrawerVisible: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        displayName: undefined,
        deptId: undefined,
        cn: undefined,
        searchScope: "current",
      },

      members: {
        list: [],
        total: 0,
        query: {
          samAccountName: undefined,
          displayName: undefined,
          pageNum: 1,
          pageSize: 10,
        },
        loading: false,
      },
      infoLoading: false,
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  mounted() {
    this.getTreeselect();
  },
  activated() {
    this.getList();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      if (!this.queryParams.cn) return;
      if (
        this.queryParams.searchScope == "global" &&
        !this.queryParams.displayName
      ) {
        this.$message.warning("全局搜索必须输入查询条件！");
        return;
      }
      this.loading = true;
      groupApi
        .pageList(this.queryParams)
        .then((res) => {
          this.userList = res.data.data;
          this.total = res.data.pagination.dataCount;
        })
        .catch()
        .finally((n) => {
          this.loading = false;
        });
    },
    getIcon(row) {
      return row.objectCategory.includes("Group") ? "ad-group" : "ad-person";
    },
    // 导出
    exportGroupExcel() {
      this.loading = true;
      groupApi
        .exportGroupExcel(this.queryParams)
        .then((res) => {
          const content = res.data;
          const blob = new Blob([content], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",
          });
          var headerVal = res.headers["content-disposition"].split(";")[1];
          const fileName = headerVal.substr("filename=".length + 1);
          if (navigator.msSaveBlob) {
            navigator.msSaveBlob(blob, fileName);
          } else {
            let url = window.URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.href = url;
            link.download = fileName;
            link.click();
            url.revokeObjectURL(link.href);
          }
        })
        .catch()
        .finally((n) => {
          this.loading = false;
        });
    },
    // 节点单击事件
    handleNodeClick(node) {
      this.queryParams.orgDN = node.data.distinguishedName;
      this.queryParams.cn = node.data.cn;
      this.queryParams.searchScope = "current";
      this.getList();
    },

    //删除成员
    handleRemoveMember(row) {
      this.$confirm(`是否确认移除组成员【${row.cn}】?`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return groupApi.removeGroupMember(
            this.currentGroup.distinguishedName,
            { members: [row.distinguishedName] }
          );
        })
        .then(() => {
          this.getMembers();
          this.msgSuccess("删除成功");
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: [],
      };
      this.resetForm("form");
    },

    //查看详细信息
    async showInfo(row) {
      this.groupDetailDrawerVisible = true;
      this.infoLoading = true;
      this.members.query.samAccountName = row.samAccountName;
      this.members.query.distinguishedName = row.distinguishedName;

      const res = await groupApi
        .info(row.samAccountName)
        .catch()
        .finally((n) => {
          this.infoLoading = false;
        });
      if (res.success) {
        this.currentGroup = res.data;

        this.getMembers();
      }
    },

    handleDeleteGroup(row) {
      this.$confirm("是否确认删除组【" + row.samAccountName + "】?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return groupApi.deleteGroup(row.samAccountName);
        })
        .then((res) => {
          if (res.success) {
            this.getList();
            this.msgSuccess("删除成功");
          }
        });
    },
    async getMembers() {
      this.members.loading = true;
      const res2 = await groupApi.membersPage(
        this.members.query.distinguishedName,
        this.members.query
      );
      if (res2.success) {
        this.members.list = res2.data.data;
        this.members.total = res2.data.pagination.dataCount;
      }
      this.members.loading = false;
    },

    handleAddGroup() {
      // const cn = this.$refs["tree"].getCurrentKey();
      const { distinguishedName } = this.$refs["tree"].getCurrentNode().data;
      this.$router.push(`/activeDirectory/group/add/${distinguishedName}`);
    },

    //跳转至成员管理
    showMembersManage() {
      const { distinguishedName } = this.currentGroup;
      const { href } = this.$router.resolve({
        path: `/activeDirectory/group/membersManage/${distinguishedName}`,
      });
      console.log(href);
      window.open(href, "_blank");
      // window.open(`activeDirectory/group/membersManage/${distinguishedName}`);
      // this.$router.push(`/activeDirectory/group/membersManage/${distinguishedName}`);
    },
  },
};
</script>
<style lang="scss" scoped>
.head-container {
  max-height: calc(100vh - 100px);
  overflow: auto;
}
</style>
